package com.WISSC.controller;


import com.WISSC.bean.IndividualEvent;
import com.WISSC.bean.Occupation;
import com.WISSC.bean.Team;
import com.WISSC.bean.layuiBean.ResultPage;
import com.WISSC.bean.layuiBean.VoPage;
import com.WISSC.commen.BaseController;
import com.WISSC.service.ConfigureService;
import com.WISSC.service.TeamMatchService;
import com.WISSC.service.TeamService;
import com.WISSC.service.WebPageService;
import com.WISSC.util.Respons.ResponseUtil;
import com.WISSC.util.date.DateUtil;
import com.WISSC.util.file.DownLoadFileUtils;
import com.WISSC.util.file.FilePath;
import com.WISSC.util.file.Picture;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 战队信息表 前端控制器
 * </p>
 *
 * @author 张凯
 * @since 2019-05-06
 */
@Controller
@RequestMapping("/team")
@Api(value = "战队赛事积分 controller", tags = "战队赛事积分")
public class TeamController extends BaseController {

    @Autowired
    TeamService teamService;
    @Autowired
    TeamMatchService teamMatchService;
    @Autowired
    WebPageService webPageService;
    @Autowired
    ConfigureService configureService;

    //跳转首页
    @RequestMapping(value = "main.html", method = RequestMethod.GET)
    public String main() {
        return "main/team";
    }

    //跳转添加
    @RequestMapping(value = "team_add.html", method = RequestMethod.GET)
    public String team_add() {
        return "add/team_add";
    }

    //跳转编辑
    @RequestMapping(value = "team_edit.html", method = RequestMethod.GET)
    public String main_edit(String teamLogo, Model model, Long id) {
        model.addAttribute("teamLogo", teamLogo);
        model.addAttribute("id", id);
        return "edit/team_edit";
    }

    //跳转战队信息
    @RequestMapping(value = "teamInfo.html", method = RequestMethod.GET)
    public String teamInfo() {
        return "team_select";
    }

    //战队信息查询登陆页面
    @RequestMapping(value = "team_login.html", method = RequestMethod.GET)
    public String team_login() {

        return "team_login";
    }

    //战队信息查询首页
    @RequestMapping(value = "team_index.html", method = RequestMethod.GET)
    public String team_index(Model model, String teamName, String city, Long id) {
        model.addAttribute("teamName", teamName);
        model.addAttribute("city", city);
        model.addAttribute("id", id);
        model.addAttribute("list", webPageService.selectAll());
        model.addAttribute("url", configureService.getById(1).getConfigure());
        return "team_index";
    }


    @RequestMapping(value = "city")
    public String city() {
        return "team/city";
    }


    //跳转战队信息
    @RequestMapping(value = "team_select.html", method = RequestMethod.GET)
    public String team_select(Model model, String teamName, String city, Long id) {
        model.addAttribute("teamName", teamName);
        model.addAttribute("city", city);
        System.out.println("id:" + id);

        Team aaaa = teamService.getById(id);
        Team team = teamService.select(teamName, city);
        if (team == null) {
            return "team/team_select";
        } else {
            String time = DateUtil.numberDateFormat(team.getBuildingTime() + "", "yyyy-MM-dd");
            model.addAttribute("data", time);
            model.addAttribute("model", team);
            List<Team> list = teamService.country(city, teamName);
            for (int i = 0; i < list.size(); i++) {
                if (i == 0) {
                    if (aaaa.getNationalRanking() == 2) {
                        model.addAttribute("county", "暂无参加排名");
                    } else {
                        model.addAttribute("county", list.get(i).getRow());
                    }

                }
                if (i == 1) {
                    if (aaaa.getProvinceRanking() == 2) {
                        model.addAttribute("county1", "暂无参加排名");
                    } else {
                        model.addAttribute("county1", list.get(i).getRow());
                    }

                }
                if (i == 2) {
                    if (aaaa.getCityRanking() == 2) {
                        model.addAttribute("county2", "暂无参加排名");
                    } else {
                        model.addAttribute("county2", list.get(i).getRow());
                    }

                }
            }
            return "team/team_select";
        }


    }

    /**
     * @param
     * @return 战队信息添加
     */
    @RequestMapping(value = "teamInsert", method = RequestMethod.POST)
    @ResponseBody
    public String teamInsert(String param1, String param2, HttpSession session) {
        Team team = JSONObject.parseObject(param1, Team.class);
        if (getUser(session).getStatus() == 2) {
            team.setType(1);
            team.setFlag(4);
        } else {
            team.setType(2);
            team.setFlag(1);
        }
        return teamService.teamInsert(param2, team);
    }

    /**
     * @param team
     * @return 战队信息删除
     */
    @RequestMapping(value = "teamDelete", method = RequestMethod.POST)
    @ResponseBody
    public Map teamDelete(@RequestBody Team team, HttpSession session) {
        Team t = teamService.getById(team.getId());
        File  file = new File(t.getTeamLogo());
        if (file.isFile() && file.exists()) {
            file.delete();
        }
        if (getUser(session).getStatus() == 2) {
            if (teamService.removeById(team)) {
                if (teamMatchService.removeByTeamId(team.getId())) {
                    return ResponseUtil.getSuccessMap();
                }
            }
        } else {
            team.setType(2);
            team.setFlag(2);
            teamService.updateById(team);
            return ResponseUtil.getSuccessMap();
        }
        return ResponseUtil.getExceptionMap();
    }

    /**
     * @param session
     * @return 个人赛事积分查询 通过idNumber查询  结果返回ResultPage
     * <p>
     * ******别动这个代码********
     */
    @RequestMapping(value = "select", method = RequestMethod.GET)
    @ResponseBody
    public ResultPage<IndividualEvent> selectByidNumber(HttpSession session) {
        List list = new ArrayList();
        list = teamService.selectByName(session);
        ResultPage rp = new ResultPage();
        rp.setCount(list.size());
        rp.setCode(0);
        rp.setMsg(":");
        rp.setData(list);
        return rp;
    }

    /**
     * @param session
     * @return 战队赛事积分查询 通过teamName查询
     */
    @RequestMapping(value = "selectByteamName", method = RequestMethod.GET)
    @ResponseBody
    public List<Team> selectByteamName(HttpSession session) {
        return teamService.selectByName(session);
    }

    /**
     * @return 学员信息修改
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public Map update(String param1, String param2, HttpSession session) {
        Team team = JSONObject.parseObject(param1, Team.class);
        if (getUser(session).getStatus() == 2) {
            team.setType(1);
            team.setFlag(4);
            return teamService.updateTeam(team, param2);
        } else {
            Team t = new Team();
            t.setTeamName(team.getTeamName());
            t.setBuildingTime(team.getBuildingTime());
            t.setCity(team.getCity());
            t.setTeamLogo(team.getTeamLogo());
            t.setTeamLevel(team.getTeamLevel());
            t.setCityRanking(team.getCityRanking());
            t.setProvinceRanking(team.getProvinceRanking());
            t.setNationalRanking(team.getNationalRanking());
            t.setBeforeId(team.getId());
            t.setFlag(3);
            t.setType(2);
            String[] split = param2.split("-");
            List list = new ArrayList();
            for (int j = 0; j < split.length; j++) {
                list.add(split[j]);
            }
            String param3 = "";
            for (int j = 0; j < list.size(); j++) {
                String arr = (String) list.get(j);
                String[] str = arr.split(",");
                param3 += str[1] + "," + str[2] + "," + str[3] + "," + str[4] + "-";
            }
            teamService.teamInsert(param3, t);
            return ResponseUtil.getSuccessMap();
        }
    }

    /**
     * @param page
     * @param limit
     * @return 分页查询
     */
    @RequestMapping(value = "/selectMyPage", method = RequestMethod.GET)
    @ResponseBody
    public ResultPage<Team> selectMyPage(
            @ApiParam(name = "page", value = "页码", required = true)
            @RequestParam int page,
            @ApiParam(name = "limit", value = "查询条数", required = true)
            @RequestParam int limit, String teamName, String city, Long buildingTime, Integer teamLevel, HttpSession session) {
        boolean admin = false;
        if (getUser(session).getRoles().getRoleValue().equals("9f77d5a8-75c6-4d06-adf9-a37e727d491a")) {
            admin = true;
        }
        return teamService.findPage(page, limit, teamName, city, buildingTime, teamLevel, session, admin);
    }


    //获取图片
    @RequestMapping("/getPhoto")
    public void getPhoto(HttpServletResponse response, @RequestParam("path") String path) throws Exception {
        System.out.println("path= " + path);
        File file = new File(path);
        FileInputStream fis;
        fis = new FileInputStream(file);
        long size = file.length();
        byte[] temp = new byte[(int) size];
        fis.read(temp, 0, (int) size);
        fis.close();
        byte[] data = temp;
        response.setContentType("image/png");
        OutputStream out = response.getOutputStream();
        out.write(data);
        out.flush();
        out.close();
    }

    //查询战队赛事积分查询
    @RequestMapping(value = "selectByTeamId", method = RequestMethod.GET)
    @ResponseBody
    public Team selectByTeamId(@RequestParam int id) {

        return teamService.getById(id);
    }

    /**
     * @param
     * @return 战队赛事登录
     */
    @RequestMapping(value = "land", method = RequestMethod.GET)
    @ResponseBody
    public List<Team> login(String teamName) {
        return teamService.login(teamName);
    }


    /**
     * @param voPage
     * @param session
     * @return 战队赛事表格查询
     */
    /*@RequestMapping(value = "selectMyPageTeam", method = RequestMethod.GET)
    @ResponseBody
    public ResultPage<Team> selectMyPageTeam(VoPage voPage, String teamName) {

        return teamService.selectMyPage(teamName, voPage);
    }*/

    /**
     * @param id
     * @return 回显所在地区
     */
    @RequestMapping(value = "getTeamCity", method = RequestMethod.POST)
    @ResponseBody
    public Map getTeamCity(Long id) {
        return teamService.getTeamCity(id);
    }


    //批量删除
    @RequestMapping(value = "deleteBtId", method = RequestMethod.POST)
    @ResponseBody
    public Map deleteById(String ids, HttpSession sessions) {
        String[] a = ids.split(",");
        for (int i = 1; i < a.length; i++) {
            Team t = teamService.getById(a[i]);
            File  file = new File(t.getTeamLogo());
            if (file.isFile() && file.exists()) {
                file.delete();
            }
        }
        if (getUser(sessions).getStatus() == 2) {
            for (int i = 1; i < a.length; i++) {
                teamService.removeById(a[i]);
                Team team = new Team();
                team.setId(Long.parseLong(a[i]));
                teamMatchService.removeByTeamId(team.getId());
            }
            return ResponseUtil.getSuccessMap();
        } else {
            for (int i = 1; i < a.length; i++) {
                Team team = new Team();
                team.setId(Long.parseLong(a[i]));
                team.setType(2);
                team.setFlag(2);
                teamService.updateById(team);
            }
            return ResponseUtil.getSuccessMap();

        }
    }


    /**
     * @param voPage
     * @param teamName
     * @return 新 战队查询
     */
    @RequestMapping(value = "selectTeamName", method = RequestMethod.GET)
    @ResponseBody
    public ResultPage<Team> selectTeamName(VoPage voPage, String teamName) {
        return teamService.selectTeamName(voPage, teamName);
    }

    //生成海报
    @RequestMapping(value = "getPoster", method = RequestMethod.GET)
    @ResponseBody
    public void getPoster(String sum, String teamName, HttpServletResponse response) throws Exception {
        List<Team> list = teamService.getTeam(teamName);
        String str = "";
        for (int i = 0; i < list.size(); i++) {
            String res = "";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            res = simpleDateFormat.format(list.get(i).getMatchTime());
            str += "赛事日期：" + res + " 赛事名称：" + list.get(i).getMatchName() + " 赛事名次：" + list.get(i).getRanking() + " 赛事积分：" + list.get(i).getIntegral() + "=";
        }
        String body = sum + "=" + str;
        String url = FilePath.getPath("team");
        String[] split = url.split("/");
        String aa = "";
        String bb = url + ".jpg";
        for (int i = 0; i < split.length; i++) {
            if (i == split.length - 1) {
                aa = split[i] + ".jpg";
            }
        }
        new Picture().createImage(body, new Font("黑体", Font.BOLD, 18), new File(url + ".jpg"));
        DownLoadFileUtils.downloadFile(response, bb, aa);
    }

    //通过
    @RequestMapping(value = "adopt", method = RequestMethod.POST)
    @ResponseBody
    public Map abopt(@RequestBody Team team) {
        Team t = teamService.getById(team);
        if (t.getFlag() == 2) {
            if (teamService.removeById(team) && teamMatchService.removeByTeamId(t.getId())) {
                return ResponseUtil.getSuccessMap();
            }
        } else if (t.getFlag() == 1) {
            team.setType(1);
            team.setFlag(4);
            if (teamService.updateById(team)) {
                return ResponseUtil.getSuccessMap();
            }
        } else {
            team.setType(1);
            team.setFlag(4);
            teamService.updateById(team);
            if (teamService.removeById(t.getBeforeId()) && teamMatchService.removeByTeamId(t.getBeforeId())) {
                return ResponseUtil.getSuccessMap();
            }
        }
        return ResponseUtil.getExceptionMap();
    }

    //不通过
    @RequestMapping(value = "noAdopt", method = RequestMethod.POST)
    @ResponseBody
    public Map noAdopt(@RequestBody Team team) {

        Team t = teamService.getById(team);
        if (t.getFlag() == 2) {
            t.setFlag(4);
            t.setType(1);
            if (teamService.updateById(t)) {
                return ResponseUtil.getSuccessMap();
            }

        } else if (t.getFlag() == 1) {
            if (teamService.removeById(team) && teamMatchService.removeByTeamId(team.getId())) {
                return ResponseUtil.getSuccessMap();
            }
        } else {
            if (teamService.removeById(team) && teamMatchService.removeByTeamId(team.getId())) {
                return ResponseUtil.getSuccessMap();
            }
        }

        return ResponseUtil.getExceptionMap();
    }
}
